package com.examiner.controller;

import com.examiner.bean.*;
import com.examiner.bean.Do.RoleMenuDo;
import com.examiner.page.QueryInfo;
import com.examiner.result.EmptyObject;
import com.examiner.result.Result;
import com.examiner.service.CommonPersonService;
import com.examiner.service.RoleMenuService;
import com.examiner.token.JwtUtil;
import org.hibernate.Session;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/commonPerson")
public class CommonPersonController {

    @Resource
    private CommonPersonService commonPersonService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private RoleMenuService roleMenuService;

    @PersistenceContext
    private EntityManager entityManager;

    /*
     *  Login 登录
     *   code: 1001     msg: 判断该用户名已存在
     *   code: 1002     msg: 判断该用户名不存在
     *   code: 1003      msg: 登录密码错误
     *   code: 1004     msg: 修改密码失败
     *   CODE: 1005     MSG: 不存在当前用户名的用户
     *   CODE: 1006     MSG: 添加失败
     *   CODE: 1007     MSG: 删除失败
     *   CODE: 1008     MSG: 当前用户id不存在
     * */

    // 查看登录用户名是否存在
    @PostMapping("/hasUserName/{commonPersonUserName}")
    public Result<EmptyObject> hasUserNam(@PathVariable("commonPersonUserName")String commonPersonUserName){
        // 验证是否存在
        CommonPerson commonPerson =  commonPersonService.hasUserName(commonPersonUserName);
        if (commonPerson == null){
            return Result.RESULT(1002,"判断该用户名不存在",false,null);
        }
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 登录
     * @param commonPerson
     * @param response
     * @return
     */
    @PostMapping("/login")
    public Result<Object> login(@RequestBody CommonPerson commonPerson, HttpServletResponse response){
        // 根据userName 查询用户
        System.out.println(passwordEncoder.encode(commonPerson.getPassword()));
        CommonPerson person = commonPersonService.hasUserName(commonPerson.getUserName());
        // 判断密码是否正确
        if (person == null){
            return Result.RESULT(1003,"用户不存在",false,null);
        }
        boolean matches = passwordEncoder.matches(commonPerson.getPassword(), person.getPassword());
        if (!matches) return Result.RESULT(1003,"密码错误，登录失败",false,null);
        // 返回 token
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName",person.getUserName());
        claims.put("role",person.getRole());
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), "examiner", null, claims);
        response.addHeader("token",token);
        List<RoleMenuDo> roleList = roleMenuService.getRoleList(person.getRole());
        if (!person.getHasTestDb()){
            for (RoleMenuDo item : roleList) {
                if (item.getMenuName().equals("考评管理"))
                    for (RoleMenu child : item.getChildren()) {
                        if ( child.getMenuName().equals("考评库")){
                            System.out.println(item.getChildren().remove(child));
                            break;
                        }
                    }
            }
        }
        if (!person.getHasNewText()){
            for (RoleMenuDo item : roleList) {
                if (item.getMenuName().equals("考评管理"))
                    for (RoleMenu child : item.getChildren()) {
                        if ( child.getMenuName().equals("新建考评")){
                            System.out.println(item.getChildren().remove(child));
                            break;
                        }
                    }
            }
        }
        Session session = entityManager.unwrap(org.hibernate.Session.class);
        session.evict(person);
        person.setPassword("");
        // 返回当前用户信息
        Map<String, Object> data = new HashMap<>();
        data.put("user",person);
        data.put("token",token);
        data.put("roleList",roleList);
        return Result.RESULT(200,"登录成功",true,data);
    }

    /**
     * 检查原密码是否正确
     * @param oldPassword
     * @return
     */
    @PostMapping("/checkPassword/{id}")
    public Result<EmptyObject> checkPassword(@PathVariable("id")Integer id,
                                             @RequestBody String oldPassword){
        CommonPerson one = commonPersonService.findById(id);
        // 验证密码
        if (one == null){
            // 该用户不存在
            return Result.RESULT(1002,"该用户不存在",false,null);
        }
        // 验证密码是否正确
        boolean matches = passwordEncoder.matches(oldPassword,one.getPassword());
        if (!matches){
            return Result.RESULT(1003,"密码错误",false,null);
        }
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePassword/{id}")
    public Result<EmptyObject> updatePassword(@PathVariable("id")Integer id,
                                              @RequestBody String newPassword){
        String encodePsw = passwordEncoder.encode(newPassword);
        Boolean aBoolean = commonPersonService.updateManagerPassword(id,encodePsw );
        if (!aBoolean) return Result.RESULT(1004,"修改密码失败",false,null);
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 根据用户名查信息列表
     * @param queryInfo
     * @return
     */
    @PostMapping("findByQuery")
    public Result<List<CommonPerson>> findByUserName(@RequestBody QueryInfo queryInfo){
        List<CommonPerson> list = commonPersonService.findByUserName(queryInfo);
        if (list.size() <= 0) return Result.RESULT(1005,"不存在当前用户名的用户",false,null);
        return Result.SUCCESS(list);
    }


    // 修改密码
    @PutMapping("/changePassword")
    public Result<EmptyObject> changePassword(@RequestBody CommonPersonVO commonPersonVO){
        // todo 判断当前用户是否存在
        // 根据id 获取用户信息
        CommonPerson commonPerson =  commonPersonService.findById(commonPersonVO.getId());
        //验证原密码是否正确
        boolean matches = passwordEncoder.matches(commonPersonVO.getOldPassword(), commonPerson.getPassword());
        if (!matches) return Result.RESULT(1003,"原密码错误",false,null);
        // 修改密码
        commonPerson.setPassword(passwordEncoder.encode(commonPersonVO.getNewPassword()));
        commonPersonService.changeCommonPersonInfo(commonPerson);
        return Result.SUCCESS(EmptyObject.empty);
    }

    // 修改CommonPerson信息
    @PostMapping("/changeUserInfo")
    public Result<EmptyObject> changeCommonPersonInfo(@RequestBody CommonPerson commonPerson){
        // todo 判断当前用户是否存在
        Boolean existsById = commonPersonService.existsById(commonPerson.getId());
        // 判断该用户名是否被使用
        if (!existsById){
            return Result.RESULT(1002,"该用户名不存在",false,null);
        }
        // 修改信息
        CommonPerson reCom = commonPersonService.changeCommonPersonInfo(commonPerson);
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 添加 commonPerson
     * @param commonPerson
     * @return
     */
    @PostMapping("/addCommonPerson")
    public Result<EmptyObject> addCommonPerson(@RequestBody CommonPerson commonPerson){
        System.out.println(commonPerson);
        CommonPerson commonPerson1 = commonPersonService.hasUserName(commonPerson.getUserName());
        if (commonPerson1 !=null ) return Result.RESULT(1001,"该用户名已存在",false,null);
        commonPerson.setPassword(passwordEncoder.encode("1"));
        commonPerson.setRole("commonPerson");
        commonPerson.setEid(1);
        commonPerson.setExaminer("e1");
        commonPerson.setState(false);
        CommonPerson add = commonPersonService.addCommonPerson(commonPerson);
        if (add == null) return Result.RESULT(1006,"添加失败",false,null);
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 删除
     * @param commonPersonId
     * @return
     */
    @DeleteMapping("/removeCommonPerson/{commonPersonId}")
    public Result<EmptyObject> removeCommonPerson(@PathVariable("commonPersonId")Integer commonPersonId){
        // 判断该用户是否存在
        Boolean existsById = commonPersonService.existsById(commonPersonId);
        if (!existsById) return Result.RESULT(1008,"当前用户id不存在",false,null);
        Boolean check = commonPersonService.removeCommonPerson(commonPersonId);
        // 判断是否删除成功
        if (check) return Result.RESULT(1007,"删除失败",false,null);
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 修改状态，动态删除
     * @param commonPersonId
     * @param state
     * @return
     */
    @PostMapping("/changeState/{commonPersonId}/{state}")
    public Result<EmptyObject> changeState(@PathVariable("commonPersonId")Integer commonPersonId,
                                           @PathVariable("state")Boolean state){
        // 判断该用户是否存在
        Boolean existsById = commonPersonService.existsById(commonPersonId);
        if (!existsById) return Result.RESULT(1008,"当前用户id不存在",false,null);
        // 改变状态
        commonPersonService.changeCommonPersonState(commonPersonId,state);
        return Result.SUCCESS(EmptyObject.empty);
    }

    @PostMapping("/changeCommonPersonHasTestDB/{commonPersonId}/{hasTestDb}")
    public Result<Object> changeCommonPersonHasTestDB(@PathVariable("commonPersonId")Integer commonPersonId,
                                                      @PathVariable("hasTestDb")Boolean hasTestDb){
        CommonPerson byId = commonPersonService.findById(commonPersonId);
        if (byId == null) return Result.RESULT(1008,"当前用户id不存在",false,null);
        byId.setHasTestDb(hasTestDb);
        commonPersonService.addCommonPerson(byId);
        return Result.RESULT(200,"更改考评库权限成功",true,null);
    }

    @PostMapping("/changeCommonPersonHasNewText/{commonPersonId}/{hasNewText}")
    public Result<Object> changeCommonPersonHasNewText(@PathVariable("commonPersonId")Integer commonPersonId,
                                                      @PathVariable("hasNewText")Boolean hasNewText){
        CommonPerson byId = commonPersonService.findById(commonPersonId);
        if (byId == null) return Result.RESULT(1008,"当前用户id不存在",false,null);
        byId.setHasNewText(hasNewText);
        commonPersonService.addCommonPerson(byId);
        return Result.RESULT(200,"更改新建考评权限成功",true,null);
    }

    @PostMapping("/changeAllState")
    public Result<Object> changeAllState(){
        try {
            commonPersonService.changeAllState();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.RESULT(201,"恢复用户选取状态失败",false,null);
        }
        return Result.RESULT(200,"恢复用户选取状态成功",true,null);
    }

    // 根据部门id获取所有部门成员
    @PostMapping("/getCommonPersonListByDepartment/{id}")
    public Result<Object> getCommonPersonListByDepartment(@PathVariable("id") Integer id){
        List<CommonPerson> commonPersonList;
        try{
            commonPersonList = commonPersonService.findBySidAndStype(id,"部门");
        }catch (Exception e){
            e.printStackTrace();
            return Result.RESULT(201,"查询当前部门的所有成员失败",true,null);
        }
        return Result.RESULT(200,"成功查询当前部门的所有成员",true,commonPersonList);
    }

    /**
     * 根据id查询当前职位
     * @param id
     * @return
     */
    @PostMapping("/getCommonPersonById/{id}")
    public Result<Object> getCommonPersonById(@PathVariable("id")Integer id){
        CommonPerson commonPerson;
        try{
            commonPerson = commonPersonService.findById(id);
        }catch (Exception e){
            e.printStackTrace();
            return Result.RESULT(201,"获取成员信息失败",false,null);
        }
        if (commonPerson == null){
            return Result.RESULT(201,"当前成员不存在",false,null);
        }
        return Result.RESULT(200,"成功获取成员信息",true,commonPerson);
    }
}
